package simulation;

import proxy.Link;
import proxy.ServerNode;

/**
 * Calculates the minimum hop distance between two servers
 * If connections are asymmetric, this function is not commutative
 * @author wilfried
 */
public class HopDist {
	private int minDist= Integer.MAX_VALUE;

	ServerNode server1;
	ServerNode server2;
	
	public HopDist(ServerNode server1, ServerNode server2, Simulator simulator) {
		this.server1 = server1;
		this.server2 = server2;
		nodeVisitor(server1, 0);
		// mark server nodes as unvisited
		for (ServerNode n: simulator.getNodes()) 
			n.setHopLevel(Integer.MAX_VALUE);
		//recurse to find minDist
		nodeVisitor(server1,0);
		if (minDist == Integer.MAX_VALUE) minDist=-1;
	};
	
	void nodeVisitor(ServerNode n, int hopDist) {
		if (hopDist > n.getHopLevel()) return;
		n.setHopLevel(hopDist);
		
		if (n.equals(server2)) {
			if (hopDist < minDist)
				minDist = hopDist;
		}
		else {
			hopDist++;
			for (Link link:n.getLinks()) 
				nodeVisitor(link.getTargetNode(),hopDist);
		}
	}
	
	public int getMinDist() {
		return minDist;
	}
	
}
